package com.erbao.disruptor;

import com.lmax.disruptor.*;
import com.lmax.disruptor.dsl.Disruptor;

import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author CaoBaoYin
 * @since 22/3/10 10:51
 */
public class MainHandlerException {

    public static void main(String[] args) {
        // 创建工厂
        LongEventFactory longEventFactory = new LongEventFactory();
        // 队列大小
        int ringBufferSize = 1024;
        // 创建disruptor。线程工厂里创建线程，在这个线程里调用消费者，不同的消费者会在不同的线程
        Disruptor<LongEvent> disruptor = new Disruptor<LongEvent>(longEventFactory, ringBufferSize, Executors.defaultThreadFactory());
        // 指定消费者
        EventHandler handler = (event, sequence, endOfBatch) -> {
            System.out.println(event);
            throw new RuntimeException("消费者故意抛出异常");
        };
        disruptor.handleEventsWith(handler);

        // 异常处理
        disruptor.handleExceptionsFor(handler).with(new ExceptionHandler<LongEvent>() {
            /*消费者异常处理*/
            @Override
            public void handleEventException(Throwable ex, long sequence, LongEvent event) {
                System.out.println("处理异常："+ex.getMessage());
            }

            /*disruptor启动的时候异常*/
            @Override
            public void handleOnStartException(Throwable ex) {

            }

            /*disruptor关闭的时候异常*/
            @Override
            public void handleOnShutdownException(Throwable ex) {

            }
        });

        // 启动
        disruptor.start();

        // 生产event
        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();
        // 不带参数
        EventTranslator<LongEvent> translator = new EventTranslator<LongEvent>() {
            @Override
            public void translateTo(LongEvent event, long sequence) {
                event.setValue(1000L);
            }
        };
        ringBuffer.publishEvent(translator);


        try {
            disruptor.shutdown(5L, TimeUnit.SECONDS);
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

    }

}
